import { FieldSelect } from '@/components/Common/FlowDesign/Config/Components/Rule/modal/FieldSelect';
import FullScreenModal from '@/components/Common/fullScreen';
import OpenFileDialog from '@/components/OpenFileDialog';
import { model, schema } from '@/ts/base';
import { IMallTemplate } from '@/ts/core/thing/standard/page/mallTemplate';
import { Button, Card, Input, Space, Typography } from 'antd';
import _ from 'lodash';
import React, { useEffect, useRef, useState } from 'react';
import { AiOutlineCloseCircle } from 'react-icons/ai';
import cls from './index.module.less';

interface IProps {
  current: IMallTemplate;
  finished: () => void;
}

interface IRenderCard {
  current: IMallTemplate;
  keyword: 'form' | 'hot' | 'work' | 'text' | 'borrow' | 'splitField';
  title: string;
  name: string;
  accepts: string[];
}

const RenderCard = (props: IRenderCard) => {
  const [center, setCenter] = useState(<></>);
  const [fields, setFields] = useState<any[]>([]);
  const [target, setTarget] = useState<model.MappingData>();
  const [bind, setBind] = useState(props.current.metadata.params?.[props.keyword]);
  useEffect(() => {
    const id = props.current.subscribe(() => {
      setBind(props.current.metadata.params?.[props.keyword]);
    });
    return () => {
      props.current.unsubscribe(id);
    };
  }, []);

  useEffect(() => {
    const current = props.current;
    const getFields = async () => {
      if (!current.metadata?.params) return;
      const { form, hot, splitField } = current.metadata.params;
      setTarget(splitField);
      const ids = [form?.id, hot?.id].filter(Boolean);
      if (ids.length === 0) return;

      try {
        const res = await Promise.all(
          ids.map((id) => current.directory.resource.formColl.find([id])),
        );
        const fields = _.uniqBy(
          res.flatMap((item) => item?.[0]?.attributes || []),
          'id',
        ).filter((attr: any) => ['数值型', '货币型'].includes(attr.valueType));
        setFields(fields);
      } catch (error) {
        console.error('获取字段失败:', error);
      }
    };
    getFields();
  }, [props.current]);

  const boxName = useRef<any>();
  const renderList = (_bind: schema.Binding) => {
    return (
      <div className={cls.row} key={_bind.id}>
        <Typography.Text
          style={{
            fontSize: 14,
            width: '200px',
            lineHeight: '24px',
            color: '#888',
          }}
          title={_bind?.name as string}
          ellipsis>
          {_bind?.name}
        </Typography.Text>
        {!!_bind?.name && (
          <div className={cls.closeIconWrapper}>
            <AiOutlineCloseCircle
              onClick={() => {
                props.keyword === 'splitField' && setTarget(undefined)
                props.current.update({
                  ...props.current.metadata,
                  params: {
                    ...props.current.metadata.params,
                    [props.keyword]: Array.isArray(bind)
                      ? bind.filter((work) => work.id !== _bind.id)
                      : undefined,
                  },
                });
              }}
            />
          </div>
        )}
      </div>
    );
  };
  return (
    <>
      <Space direction="vertical" size="middle" style={{ width: '100%' }}>
        <Card
          type="inner"
          title={
            <div>
              <span>{props.title}</span>
            </div>
          }
          bodyStyle={{ padding: '12px' }}
          extra={
            <>
              {props.keyword !== 'splitField' && (
                <a
                  onClick={() => {
                    setCenter(
                      <OpenFileDialog
                        title={`选择`}
                        accepts={props.accepts}
                        rightShow={false}
                        rootKey={props.current.directory.key}
                        showFile
                        onCancel={() => setCenter(<></>)}
                        onOk={async (files) => {
                          if (files.length > 0) {
                            const file = files[0].metadata as any;
                            const _data = {
                              id: file.id,
                              name: file.name,
                              directoryId: file.directoryId,
                              applicationId: file.applicationId ?? file.directoryId,
                              typeName: file.typeName,
                            };
                            if (props.keyword === 'work') {
                              let work = props.current.metadata.params?.[props.keyword];
                              if (work) {
                                if (!Array.isArray(work)) {
                                  work = [work];
                                }
                              } else {
                                work = [];
                              }
                              await props.current.update({
                                ...props.current.metadata,
                                params: {
                                  ...props.current.metadata.params,
                                  [props.keyword]: [...work, _data],
                                },
                              });
                            } else {
                              await props.current.update({
                                ...props.current.metadata,
                                params: {
                                  ...props.current.metadata.params,
                                  [props.keyword]: _data,
                                },
                              });
                            }
                          }
                          setCenter(<></>);
                        }}
                      />,
                    );
                  }}>
                  绑定
                </a>
              )}
            </>
          }>
          {props.keyword === 'splitField' && (
            <FieldSelect
              style={{ flex: 'auto' }}
              value={target}
              onChange={async (e: model.MappingData) => {
                setTarget(e);
                await props.current.update({
                  ...props.current.metadata,
                  params: {
                    ...props.current.metadata.params,
                    [props.keyword]: e,
                  },
                });
              }}
              data={fields}
            />
          )}

          {(props.keyword == 'form' || (props.keyword == 'hot' && props.name)) && (
            <div style={{ marginBottom: 10 }}>
              <div
                style={{
                  fontSize: 12,
                  width: '200px',
                  lineHeight: '24px',
                  color: '#888',
                  marginBottom: 5,
                }}>
                区块标题
              </div>
              <Input.Group compact>
                <Input
                  placeholder="请输入区块标题"
                  style={{ width: 'calc(100% - 100px)' }}
                  defaultValue={props.current.metadata?.params?.[props.name] ?? ''}
                  onChange={(e) => {
                    boxName.current = e.target.value;
                  }}
                />
                <Button
                  type="primary"
                  onClick={(e) => {
                    props.current.update({
                      ...props.current.metadata,
                      params: {
                        ...props.current.metadata.params,
                        [props.name]: boxName.current,
                      },
                    });
                  }}>
                  保存
                </Button>
              </Input.Group>
            </div>
          )}
          {bind ? (
            Array.isArray(bind) ? (
              bind.map((item) => {
                return renderList(item);
              })
            ) : (
              renderList(bind as schema.Binding)
            )
          ) : (
            <></>
          )}
        </Card>
      </Space>
      {center}
    </>
  );
};

const TemplateModal: React.FC<IProps> = ({ current, finished }) => {
  return (
    <FullScreenModal
      open
      centered
      fullScreen={false}
      width={'80vw'}
      bodyHeight={'80vh'}
      destroyOnClose
      title={'商城模板配置'}
      onCancel={() => finished()}>
      <div className={cls.templateModal}>
        <div className={cls.config}>
          <RenderCard
            keyword={'form'}
            current={current}
            title={'常规商品'}
            accepts={['表单']}
            name={'boxName1'}
          />
          <RenderCard
            keyword={'hot'}
            current={current}
            title={'热度商品'}
            accepts={['表单']}
            name={'boxName2'}
          />
          <RenderCard
            keyword={'work'}
            current={current}
            title={'领用办事'}
            accepts={['办事']}
            name=""
          />
          <RenderCard
            keyword={'borrow'}
            current={current}
            title={'借用办事'}
            accepts={['办事']}
            name=""
          />
          <RenderCard
            keyword={'splitField'}
            current={current}
            title={'拆分的字段'}
            accepts={[]}
            name=""
          />
        </div>
      </div>
    </FullScreenModal>
  );
};

export default TemplateModal;
